﻿#include <eventloop.h>
#include "workcondition.h"

WorkCondition::WorkCondition(unsigned int WorkCount)
{
    m_workCount = WorkCount;
}

void WorkCondition::AddWork()
{
    std::lock_guard<std::recursive_mutex> lock(m_mutex);
    m_workCount ++;
}

void WorkCondition::FinishWork()
{
    std::unique_lock<std::recursive_mutex> lock(m_mutex);
    m_workCount--;
    if(!m_workCount){
        m_con.notify_all();
    }

	for (auto &i : wait_loop) {
		i->exit(0);
	}

	wait_loop.clear();
}

void WorkCondition::WaitForFinished(bool isAlive)
{
	if (isAlive) {
		EventLoop loop;
		{
			std::unique_lock<std::recursive_mutex> lock(m_mutex);
			if (m_workCount) {
				wait_loop.insert(&loop);
				loop.exec();
			}
		}
	}
	else {
		std::unique_lock<std::recursive_mutex> lock(m_mutex);
		if (m_workCount) {
			m_con.wait(lock);
		}
	}
}

WorkConditionGurad::WorkConditionGurad(WorkCondition &w):m_work(w)
{
    m_work.AddWork();
}

WorkConditionGurad::~WorkConditionGurad()
{
    m_work.FinishWork();
}
